package cn.imokay.juc.lock;

import java.util.concurrent.TimeUnit;

/**
 * 死锁示例，通过jps -l 列出所有Java进程，获得进程ip，再通过jstack pid查看进程的堆栈，可查看是否死锁
 * 或者通过jconsole窗口线程中查看死锁
 */
public class DeadLock {
    public static void main(String[] args) {
        Object a = new Object();
        Object b = new Object();

        new Thread(() -> {
            synchronized (a) {
                System.out.println(Thread.currentThread().getName() + "\t---持有a锁，希望获得b锁");
                try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace();}
                synchronized (b) {
                    System.out.println(Thread.currentThread().getName() + "\t---成功获得b锁");
                }
            }

        },"A").start();

        new Thread(() -> {
            synchronized (b) {
                System.out.println(Thread.currentThread().getName() + "\t---持有b锁，希望获得a锁");
                try { TimeUnit.SECONDS.sleep(1); } catch (Exception e) { e.printStackTrace();}
                synchronized (a) {
                    System.out.println(Thread.currentThread().getName() + "\t---成功获得a锁");
                }
            }

        },"B").start();
    }
}
